# -*- coding: utf-8 -*-
# backend/api/file_routes.py
from typing import Dict, Any
from fastapi import APIRouter, HTTPException, Depends
from pydantic import BaseModel, Field

from backend.core.services.project_service import project_service
from backend.utils.security import get_current_user_id


router = APIRouter()


class FileSaveRequest(BaseModel):
    """文件保存请求"""
    content: str = Field(description="文件内容")


@router.get("/{file_id}", response_model=Dict[str, Any])
async def get_file_content(
    file_id: str,
    user_id: str = Depends(get_current_user_id)
):
    """获取文件内容"""
    try:
        result = await project_service.get_file_content(file_id, user_id)
        
        return {
            "code": 200,
            "msg": "成功",
            "data": {
                "id": result["id"],
                "name": result["name"],
                "path": result["path"],
                "content": result["content"],
                "size": result["size"],
                "created_at": result["created_at"].isoformat(),
                "updated_at": result["updated_at"].isoformat()
            }
        }
    
    except Exception as e:
        raise HTTPException(
            status_code=404 if "不存在" in str(e) else 500,
            detail={
                "code": 40401 if "不存在" in str(e) else 50001,
                "msg": str(e),
                "data": None
            }
        )


@router.put("/{file_id}", response_model=Dict[str, Any])
async def save_file(
    file_id: str,
    request: FileSaveRequest,
    user_id: str = Depends(get_current_user_id)
):
    """保存文件"""
    try:
        success = await project_service.save_file(
            file_id=file_id,
            content=request.content,
            user_id=user_id
        )
        
        if success:
            return {
                "code": 200,
                "msg": "保存成功",
                "data": {
                    "file_id": file_id,
                    "save_time": "2024-10-01 10:30:00"  # 应该使用实际时间
                }
            }
        else:
            raise Exception("保存失败")
    
    except Exception as e:
        raise HTTPException(
            status_code=500,
            detail={
                "code": 50001,
                "msg": f"保存文件失败: {str(e)}",
                "data": None
            }
        )


@router.delete("/{file_id}", response_model=Dict[str, Any])
async def delete_file(
    file_id: str,
    user_id: str = Depends(get_current_user_id)
):
    """删除文件"""
    try:
        success = await project_service.delete_file(file_id, user_id)
        
        if success:
            return {
                "code": 200,
                "msg": "删除成功",
                "data": {
                    "file_id": file_id
                }
            }
        else:
            raise Exception("删除失败")
    
    except Exception as e:
        raise HTTPException(
            status_code=500,
            detail={
                "code": 50001,
                "msg": f"删除文件失败: {str(e)}",
                "data": None
            }
        )
